package com.letoken.platform.repo.app.redis;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.letoken.platform.pub.constant.RedisKeyConstant;
import com.letoken.platform.pub.util.BeanUtil;
import com.letoken.platform.repo.admin.po.AdminRechargeConfig;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @version 1.0
 * @author： letokenlabs
 * @date： 2021/11/24 9:55
 * 用户登录凭证
 */
public class RechargeConfigTokenRedis {
    private StringRedisTemplate stringRedisTemplate;

    private final HashOperations<String, String, String> valueOps;

    private RechargeConfigTokenRedis() {
        stringRedisTemplate = BeanUtil.getBean(StringRedisTemplate.class);
        this.valueOps = stringRedisTemplate.opsForHash();
    }

    private enum Singleton {
        INSTANCE;
        private RechargeConfigTokenRedis instance;

        // JVM会保证此方法绝对只调用一次
        Singleton() {
            instance = new RechargeConfigTokenRedis();
        }
    }

    /**
     * 活动配置
     */
    String cacheKey = RedisKeyConstant.RECHARGE_CONFIG;

    public static RechargeConfigTokenRedis me() {
        return RechargeConfigTokenRedis.Singleton.INSTANCE.instance;
    }

    public AdminRechargeConfig getValue(Integer tokenId) {
        String valueStr = valueOps.get(cacheKey, tokenId.toString());
        AdminRechargeConfig rechargeConfig = null;
        if (StrUtil.isNotBlank(valueStr)){
            try {
                rechargeConfig = JSONObject.toJavaObject(JSONObject.parseObject(valueStr), AdminRechargeConfig.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return rechargeConfig;
    }

    public void putValue(Integer tokenId, String value) {
        if (StrUtil.isNotBlank(value)){
            valueOps.put(cacheKey, tokenId.toString(), value);
        }
    }

}
